//
//  TGUserModel.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/5/6.
//

#import "TGUserModel.h"
//#import "AESEncryption.h"

static TGUserModel *_userEntity =nil;
#define TOKEN_KEY [NSString stringWithFormat:@"ios%@",@"TOKEN"].qmui_md5
@implementation TGUserModel

-(instancetype)init{
    if (self = [super init]) {
        
    }
    return self;
}
//- (NSString *)token{
//    return @"MTUyNzgxMzc2MTAxNjM1NzAwMDY0NzU2";
//}
- (NSString *)getToken {
    return self.accessToken[@"tokenValue"];
}


//重写以下几个方法
- (void)encodeWithCoder:(NSCoder*)aCoder {
    [self modelEncodeWithCoder:aCoder];
}

- (id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super init];
    return [self modelInitWithCoder:aDecoder];
}

- (id)copyWithZone:(NSZone*)zone {
    return [self modelCopy];
}

- (NSUInteger)hash {
    return [self modelHash];
}

- (BOOL)isEqual:(id)object {
    return [self modelIsEqual:object];
}


+ (void)remove {
    YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:[TGUserModel path]];
    [diskCache removeObjectForKey:[[NSBundle mainBundle] bundleIdentifier]];
    _userEntity = nil;
}

+ (void)refreshTokenWithComplemention:(ComplentValueBlock)complemention {
    
    NSString *url = APP_URL;
    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
    if (!EmptyCheck(testUrl)) {
        url = testUrl;
    }
    
    TGUserModel *oldUserModel = [TGUserModel getUserEntity];
    if (oldUserModel != nil && oldUserModel.refreshToken != nil) {
        [TGNetworkManager startRequestWithURL:[NSString stringWithFormat:@"%@api/login/refreshToken", url] method:@"POST" paramters:@{@"refreshToken": R(oldUserModel.refreshToken[@"tokenValue"])} success:^(TGResponseItem *responseItem) {
            NSLog(@"---%@", responseItem.data);
            [TGGCD executeMainAsyncTask:^{
                if (responseItem.success) {
                    TGUserModel *nowUserModel = [TGUserModel modelWithJSON:responseItem.data];
                    nowUserModel.getAliasSeq = oldUserModel.getAliasSeq;//存储别名序列号
                    nowUserModel.authoritiesModel = [oldUserModel getAuthoritiesModel];
                    [TGUserModel save:nowUserModel];
                }
//                complemention(@"GSE_003");
                complemention(responseItem.errorCode?:@"1");
            }];
        } failure:^(NSError *error) {
            complemention(@"0");
        }];
    } else {
        complemention(@"0");
    }

}

+ (NSString *)path {
    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) firstObject];
    basePath = [basePath stringByAppendingPathComponent:@"通冠用户名".qmui_md5];
    return basePath;
}

+ (TGUserModel *)getUserEntity{
    if (_userEntity) {
        return _userEntity;
    }
    YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:[self path]];
    _userEntity = (id)[diskCache objectForKey:[[NSBundle mainBundle] bundleIdentifier]];
    if (_userEntity) {
//        [_userEntity getAuthoritiesModel];
//        _userEntity.getToken = [AESEncryption AES256Decrypt:_userEntity.getToken key:TOKEN_KEY];
    }
    return _userEntity;
}

+ (void)save{
    [self save:[self getUserEntity]];
}

+(void)update:(TGUserModel *)base{
    if (!base) {
        return;
    }
    _userEntity.getToken = base.getToken;
    [self save:_userEntity];
}
+ (void)save:(TGUserModel *)user {
    if (!user) {
        return;
    }
//    [NSUserDefaults.standardUserDefaults setObject:user.userhead forKey:user.phone];
    YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:[TGUserModel path]];
//    user.phone = [AESEncryption AES256Encrypt:user.phone key:NAME_KEY];
//    user.getToken = [AESEncryption AES256Encrypt:user.getToken key:TOKEN_KEY];
    
//    [NSUserDefaults.standardUserDefaults setObject:user.phone forKey:UserName];
    [diskCache setObject:(id)user forKey:[[NSBundle mainBundle] bundleIdentifier]];
    
    _userEntity = user;
//    _userEntity.phone = [AESEncryption AES256Decrypt:user.phone key:NAME_KEY];
//    _userEntity.getToken = [AESEncryption AES256Decrypt:user.getToken key:TOKEN_KEY];
}

 //是否是管理员
- (BOOL)administrator
{
    if ([_authorities containsObject:@"engineer_button"])
    {
        return NO;
    }
    return YES;
}
//是否是经理
-(BOOL)manager
{
    if ([_authorities containsObject:@"engineer_button"])
    {
        return NO;
    }
    return YES;
    
    
    
}

//是不是服务支持人员(索赔使用)
-(BOOL)serviceSupport
{
    
    if ([_authorities containsObject:@"engineer_button"])
    {
        return NO;
    }
    return YES;
    
}



- (void)setAuthorities:(NSArray *)authorities{
    _authorities = authorities;
}

- (TGAuthoritiesModel *)getAuthoritiesModel{
    NSString* path = [[NSBundle mainBundle] pathForResource: @"authorities"
                                                     ofType: @"json"];
    NSString* data = [NSString stringWithContentsOfFile: path
                                               encoding: NSUTF8StringEncoding
                                                  error: nil];
    NSData* resultData = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultData
                                                                options:kNilOptions
                                                                  error:nil];
    
    NSMutableDictionary *result = [NSMutableDictionary dictionaryWithDictionary:dic];
    for (NSString *managerKey in dic.allKeys) {
        NSMutableDictionary *managerDic = [[result objectForKey:managerKey] mutableCopy];
        NSDictionary *modifyDic = [dic objectForKey:managerKey];
        for (NSString *listKey in modifyDic.allKeys) {
            NSMutableDictionary *itemDic = [[managerDic objectForKey:listKey] mutableCopy];
            NSDictionary *modifyItemDic = [modifyDic objectForKey:listKey];
            for (NSString *key in modifyItemDic.allKeys) {
                if ([_authorities containsObject:key]) {
                    [itemDic setValue:@(YES) forKey:key];
                }
            }
            [managerDic setValue:itemDic forKey:listKey];
        }
        [result setValue:managerDic forKey:managerKey];
    }
    TGAuthoritiesModel *model = [[TGAuthoritiesModel alloc] init];
    model = [TGAuthoritiesModel modelWithJSON:result];
    return model;
}


- (BOOL)isAdmin{
    if ([_authorities containsObject:@"ROLE_ADMIN"]){
        return YES;
    }
    return NO;
}
// 总领导
-(BOOL)isTopLeader{
    if ([_authorities containsObject:@"ROLE_TOP_LEADER"]){
        return YES;
    }
    return NO;
}
// 宣传部人员
-(BOOL)isPublicityWorker{
    if ([_authorities containsObject:@"ROLE_PUBLICITY_WORKER"]){
        return YES;
    }
    return NO;
}
// 实地调查组
-(BOOL)isInvestigationTeam{
    if ([_authorities containsObject:@"ROLE_INVESTIGATION_TEAM"]){
        return YES;
    }
    return NO;
}
// 区领导
-(BOOL)isRegionLeader{
    if ([_authorities containsObject:@"ROLE_REGION_LEADER"]){
        return YES;
    }
    return NO;
}
// 局委领导
-(BOOL)isOrgLeader{
    if ([_authorities containsObject:@"ROLE_ORG_LEADER"]){
        return YES;
    }
    return NO;
}
// 局委工作人员
-(BOOL)isOrgWorker{
    if ([_authorities containsObject:@"ROLE_ORG_WORKER"]){
        return YES;
    }
    return NO;
}


@end
